package apptoko.com.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import apptoko.com.ListingActivity;
import apptoko.com.UILApplication;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.CategoryListSuccessEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.model.CategoryItem;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;

import com.androidquery.AQuery;
import apptoko.com.R;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

@SuppressLint("DefaultLocale")
public class CategoryFragment extends BaseFragment implements OnItemClickListener{

	private String mContent = "";
	private static final String KEY_CONTENT = "Fragment:Category";
	private CategoryAdapter adapter;
	private String currentStore;
	private BackgroundTasks bgTask;
	private AQuery aq;
	private EventBus eventBus;
	private String accessToken;
	private List<CategoryItem> catList;
	public static CategoryFragment newInstance(String content) {
		CategoryFragment fragment = new CategoryFragment();
		fragment.mContent = content;
		return fragment;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mParent = inflater.inflate(R.layout.home_category, null);
		aq = new AQuery(mParent);
		aq.id(R.id.home_cate_list).adapter(adapter).itemClicked(this).gone();
		aq.id(R.id.cat_bar).visible();
		return mParent;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, mContent);
		outState.putString(Constants.KEY_CURRENT_STORE, currentStore);
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		bgTask = new BackgroundTasks(mContext);
		eventBus = EventBus.getDefault();
		currentStore = getArguments().getString(Constants.STORE_KEY);
		catList = new ArrayList<CategoryItem>();
		adapter = new CategoryAdapter(mContext, R.layout.category_item, catList);
		EasyTracker.getInstance().setContext(mContext);
	}
	
	private void runBackgroundTask(){
		accessToken = Utils.getStaticAccessToken(getActivity());
		if(currentStore.equals("apps")){
			bgTask.getCategories(accessToken, 2, "app");
		} else if(currentStore.equals("games")){
			bgTask.getCategories(accessToken, 2, "game");
		} else if(currentStore.equals("books")){
			bgTask.getCategories(accessToken, 4, "");
		} else if(currentStore.equals("comics")){
			bgTask.getCategories(accessToken, 5, "");
		} else if(currentStore.equals("movies")){
			bgTask.getCategories(accessToken, 6, "");
		}
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		runBackgroundTask();
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
	}

	private class CategoryAdapter extends ArrayAdapter<CategoryItem> {
		
		private AQuery aq;

		public CategoryAdapter(Context context, int layout, List<CategoryItem> list) {
			super(context, layout, list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if (convertView == null) {
				convertView = li.inflate(R.layout.category_item, null);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.cat_icon);
				holder.categoryName = (TextView) convertView.findViewById(R.id.cat_name);
				holder.itemNumber = (TextView) convertView.findViewById(R.id.cat_total_item);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			CategoryItem item = getItem(position);
			aq = new AQuery(convertView);
			if(UILApplication.getInstance().isLoadAllImgs()){
				aq.id(holder.icon).visible();
				Bitmap placeholder = aq.getCachedImage(R.drawable.image_loading);
				if(aq.getCachedFile(item.getAvatar())!=null){
					aq.id(holder.icon).image(aq.getCachedFile(item.getAvatar()), 75);
					Log.e("NMN","get CategoryItem from CachedFile");
				}else{
					Log.e("NMN","get CategoryItem from server");
					aq.id(holder.icon).image(item.getAvatar(), false, true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK);
				}
				
			}else{
				aq.id(holder.icon).visibility(View.GONE);
			}
			
			aq.id(holder.categoryName).text(item.getCategoryName());
			if(item.getTotal()>0){
				aq.id(holder.itemNumber).text(String.valueOf(item.getTotal()));
			}
			return convertView;
		}
	}
	
	public static class ViewHolder{
		ImageView icon;
		TextView categoryName;
		TextView itemNumber;
	}
	
	public void onEventMainThread(CategoryListSuccessEvent event){
		List<CategoryItem> cats = event.getCategoryList();
		for(CategoryItem item : cats){
			catList.add(item);
		}
		adapter.notifyDataSetChanged();
		aq.id(R.id.cat_bar).gone();
		aq.id(R.id.home_cate_list).visible();
	}
	
	public void onEventMainThread(RequestFailEvent event){
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
		aq.id(R.id.cat_bar).gone();
		aq.id(R.id.home_cate_list).gone();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long arg3) {
		// TODO Auto-generated method stub
		if(null == view.getTag()){
			return;
		}
		CategoryItem catItem = (CategoryItem) parent.getItemAtPosition(pos);
		EasyTracker.getTracker().sendEvent(Constants.EVENT, "Category click", "category: " + catItem.getCategoryName(), Long.valueOf(1));
		Intent intent = new Intent(getActivity(), ListingActivity.class);
		intent.putExtra(Constants.CATEGORY_ID, catItem.getId());
		intent.putExtra(Constants.CATEGORY_NAME, catItem.getCategoryName());
		intent.putExtra(Constants.STORE_KEY, currentStore);
		startActivity(intent);
	}
	
}
